
import CommonService from './CommonService'
import ChromeCtl from '../Generate/ChromeCtl'

export default class AppDelegate {
  public static webRequestOnCompleted(blockingResponse:any) {
    printlog("[AppDelegate.webRequestOnCompleted] blockingResponse: ", blockingResponse)
    return blockingResponse
  }
  public static webRequestOnBeforeRequest(blockingResponse:any) {
    printlog("[AppDelegate.webRequestOnBeforeRequest] blockingResponse: ", blockingResponse)
  }
  public static webRequestOnBeforeSendHeaders(blockingResponse:any) {
    printlog("[AppDelegate.webRequestOnBeforeSendHeaders] blockingResponse: ", blockingResponse)
    return blockingResponse
  }
  // tab 更新
  public static async tabsOnUpdated(tabId:number, object:any, tab:chrome.tabs.Tab) {
    const jsonData = CommonService.jsonData
    const currentUrl = tab.url
    const objKeyArray = Object.keys(jsonData)
    if (object.status !== "complete") return
    for (const key of objKeyArray) {
      const regexPattern = new RegExp(key)
      const isMatchUrl = regexPattern.test(currentUrl)
      printlog("isMatchUrl : ", isMatchUrl)
      if (currentUrl.match(regexPattern)) {
        const theContentScriptPath = `background/${jsonData[key]}`
        printlog("[AppDelegate.tabsOnUpdated] theContentScript: ", theContentScriptPath)
        await ChromeCtl.chrometabsExecuteScript(tab.id, "file", "background/ContentScript/jquery.min.js")
        await ChromeCtl.chrometabsExecuteScript(tab.id, "file", theContentScriptPath )
        break
      }
    }
  }
  // do uncaughtException job
  public static onUncaughtException(err) {
    console.error('[AppDelegate.onUncaughtException] err', err)
  }
  // do unhandledRejection job
  public static onUnHandleRejection(reason:any, p) {
    console.error(reason, 'Unhandled Rejection at Promise', p)
  }
}
